package com.example.software.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.software.entity.Message;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MessageMapper extends BaseMapper<Message> {
    
    /**
     * 获取未读消息数量
     */
    @Select("SELECT COUNT(*) FROM message WHERE receiver_id = #{userId} AND is_read = 0")
    int getUnreadCount(@Param("userId") Long userId);
    
    /**
     * 获取最新联系人列表
     */
    @Select("SELECT DISTINCT " +
            "CASE WHEN sender_id = #{userId} THEN receiver_id ELSE sender_id END AS contact_id, " +
            "MAX(id) AS max_id " +
            "FROM message " +
            "WHERE sender_id = #{userId} OR receiver_id = #{userId} " +
            "GROUP BY contact_id " +
            "ORDER BY max_id DESC")
    List<Long> getContactIds(@Param("userId") Long userId);
    
    /**
     * 获取与某个联系人的最新消息
     */
    @Select("SELECT * FROM message " +
            "WHERE (sender_id = #{userId} AND receiver_id = #{contactId}) " +
            "OR (sender_id = #{contactId} AND receiver_id = #{userId}) " +
            "ORDER BY create_time DESC LIMIT 1")
    Message getLatestMessage(@Param("userId") Long userId, @Param("contactId") Long contactId);
    
    /**
     * 获取与某个联系人的未读消息数量
     */
    @Select("SELECT COUNT(*) FROM message " +
            "WHERE sender_id = #{contactId} AND receiver_id = #{userId} AND is_read = 0")
    int getUnreadCountByContact(@Param("userId") Long userId, @Param("contactId") Long contactId);
    
    /**
     * 获取与某个联系人的对话消息
     */
    @Select("SELECT * FROM message " +
            "WHERE (sender_id = #{userId} AND receiver_id = #{contactId}) " +
            "OR (sender_id = #{contactId} AND receiver_id = #{userId}) " +
            "ORDER BY create_time ASC")
    List<Message> getConversation(@Param("userId") Long userId, @Param("contactId") Long contactId);
}